package com.tarena.lbs.content.service.impl;

import com.tarena.lbs.activity.api.ActivityApi;
import com.tarena.lbs.activity.api.pojo.ActivityDto;
import com.tarena.lbs.base.protocol.model.Result;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.api.TagApi;
import com.tarena.lbs.basic.api.pojo.TagDto;
import com.tarena.lbs.basic.pojo.vo.TagVO;
import com.tarena.lbs.business.api.StoreApi;
import com.tarena.lbs.business.api.pojo.dto.StoreDTO;
import com.tarena.lbs.content.dao.repository.ArticleRepository;
import com.tarena.lbs.content.dao.repository.CategoryRepository;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.po.ArticleCategoryPO;
import com.tarena.lbs.content.pojo.po.ArticlePO;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 文章服务实现类
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @DubboReference
    private ActivityApi activityApi;

    @DubboReference
    private StoreApi storeApi;

    @DubboReference
    private TagApi tagApi;


    @Override
    public PageResult<ArticleVO> pageList(ArticleQuery query) {
        // 创建分页结果对象
        PageResult<ArticleVO> pageResult = new PageResult<>();

        // 调用Repository层进行分页查询
        PageInfo<ArticlePO> pageInfo = articleRepository.pageList(query);

        // 设置分页信息
        pageResult.setPageNo(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotal(pageInfo.getTotal());

        // PO转换为VO
        List<ArticleVO> vos = convertPOListToVOList(pageInfo.getList());
        pageResult.setObjects(vos);

        return pageResult;
    }
    @Override
    public ArticleVO getById(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }

        ArticlePO articlePO = articleRepository.getById(id);
        if (articlePO == null) {
            return null;
        }

        return convertPOToVO(articlePO);
    }



    /**
     * 将ArticlePO列表转换为ArticleVO列表
     */
    private List<ArticleVO> convertPOListToVOList(List<ArticlePO> pos) {
        if (pos == null || pos.isEmpty()) {
            return new ArrayList<>();
        }

        return pos.stream().map(this::convertPOToVO).collect(Collectors.toList());
    }

    /**
     * 将单个ArticlePO转换为ArticleVO
     */
    private ArticleVO convertPOToVO(ArticlePO po) {
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(po, vo);
    
        // 根据前端需求设置字段
        vo.setTitle(po.getArticleTitle()); // 设置title字段
        vo.setCategoryId(po.getArticleCategoryId()); // 设置categoryId字段
        vo.setStatus(po.getArticleStatus()); // 设置status字段
        vo.setOnlineStatus(po.getOnlineStatus()); // 设置onlineStatus字段
        vo.setArticleLabel(po.getArticleLabel()); // 添加标签字段设置
        vo.setShopId(po.getShopId()); // 设置店铺ID
        
        // 获取并设置店铺名称
        if (po.getShopId() != null) {
            try {
                // 使用Dubbo调用店铺服务获取店铺详情
                Boolean exists = storeApi.checkStoreExists(po.getShopId());
                if (exists != null && exists) {
                    List<StoreDTO> stores = storeApi.getStoresByIds(po.getShopId().toString());
                    if (stores != null && !stores.isEmpty()) {
                        vo.setShopName(stores.get(0).getStoreName());
                    }
                }
            } catch (Exception e) {
                log.error("获取店铺信息失败，shopId: {}", po.getShopId(), e);
            }
        }
    
        // 获取并设置文章分类名称
        if (po.getArticleCategoryId() != null) {
            ArticleCategoryPO categoryPO = categoryRepository.getById(po.getArticleCategoryId());
            if (categoryPO != null && categoryPO.getCategoryStatus() == 1 && categoryPO.getDeleteStatus() == 0) {
                vo.setArticleCategory(categoryPO.getCategoryName());
                vo.setCategoryName(categoryPO.getCategoryName());
            }
        }
    
        // 确保时间格式正确
        if (po.getCreateTime() != null) {
            vo.setCreateTime(po.getCreateTime());
        }
        if (po.getUpdateTime() != null) {
            vo.setUpdateTime(po.getUpdateTime());
        }
    
        return vo;
    }

    @Override
    public Result<Void> updateArticleStatus(Integer id, Integer articleStatus, Integer onlineStatus) {
        if (id == null || id <= 0) {
            return Result.fail("-1","文章ID不能为空");
        }

        // 验证状态值
        if (articleStatus != null && articleStatus != 0 && articleStatus != 1) {
            return Result.fail("-1","文章启用状态值无效");
        }

        if (onlineStatus != null && onlineStatus != 0 && onlineStatus != 1) {
            return Result.fail("-1","文章上下线状态值无效");
        }

        // 检查文章是否存在
        ArticlePO articlePO = articleRepository.getById(id);
        if (articlePO == null) {
            return Result.fail("-1","文章不存在");
        }

        // 执行更新
        int rows = articleRepository.updateStatus(id, articleStatus, onlineStatus);
        if (rows <= 0) {
            return Result.fail("-1","状态更新失败");
        }

        return Result.success();
    }

    @Override
    public Result<Void> deleteArticle(Integer id) {
        if (id == null || id <= 0) {
            return Result.fail("-1", "文章ID不能为空");
        }

        // 检查文章是否存在
        ArticlePO articlePO = articleRepository.getById(id);
        if (articlePO == null) {
            return Result.fail("-1", "文章不存在");
        }

        // 执行假删除
        int rows = articleRepository.deleteArticle(id);
        if (rows <= 0) {
            return Result.fail("-1", "删除失败");
        }

        return Result.success();
    }
    @Override
    public Result<Void> addArticle(ArticleContentParam param) {
        // 1. 参数校验
        if (param == null) {
            return Result.fail("-1", "参数不能为空");
        }
        
        if (param.getArticleTitle() == null || param.getArticleTitle().trim().isEmpty()) {
            return Result.fail("-1", "文章标题不能为空");
        }
        
        if (param.getArticleCategoryId() == null || param.getArticleCategoryId() <= 0) {
            return Result.fail("-1", "文章分类不能为空");
        }
        
        // 2. 转换参数
        ArticlePO articlePO = new ArticlePO();
        BeanUtils.copyProperties(param, articlePO);
        
        // 设置地理位置
        if (param.getLatitude() != null && param.getLongitude() != null) {
            articlePO.setLocation(param.getLatitude() + "," + param.getLongitude());
        }
        
        // 3. 调用仓库层执行新增
        int rows = articleRepository.insertArticle(articlePO);
        if (rows <= 0) {
            return Result.fail("-1", "文章新增失败");
        }
        
        return Result.success();
    }

    @Override
    public PageResult<ActivityDto> getActivityList(Integer pageNo, Integer pageSize, Integer status) {
        return activityApi.getActivityList(pageNo, pageSize, status);
    }

    @Override
    public List<StoreDTO> getStoresByBusinessId(Integer businessId) {
        // 使用Dubbo调用店铺服务获取店铺列表
        return storeApi.getStoresByBusinessId(businessId);
    }

    @Override
    public List<TagDto> getTagsByArticleId(Integer articleId) {
        return tagApi.getTagsByArticleId(articleId);
    }

    @Override
    public List<StoreDTO> getStoresByArea(List<Long> cityIdList, Integer level) {
        // 使用Dubbo调用店铺服务根据区域获取店铺列表
        return storeApi.getStoresByArea(cityIdList, level);
    }

    @Override
    public Boolean checkStoreExists(Integer storeId) {
        // 使用Dubbo调用店铺服务检查店铺是否存在
        return storeApi.checkStoreExists(storeId);
    }

    @Override
    public Result<Void> updateArticle(ArticleContentParam param) {
        // 1. 参数校验
        if (param == null || param.getId() == null || param.getId() <= 0) {
            return Result.fail("-1", "文章ID不能为空");
        }

        if (param.getArticleTitle() == null || param.getArticleTitle().trim().isEmpty()) {
            return Result.fail("-1", "文章标题不能为空");
        }

        if (param.getArticleCategoryId() == null || param.getArticleCategoryId() <= 0) {
            return Result.fail("-1", "文章分类不能为空");
        }

        // 2. 检查文章是否存在
        ArticlePO existingPO = articleRepository.getById(param.getId());
        if (existingPO == null) {
            return Result.fail("-1", "文章不存在");
        }

        // 3. 转换参数
        ArticlePO articlePO = new ArticlePO();
        BeanUtils.copyProperties(param, articlePO);

        // 设置地理位置（保持与新增相同的逻辑）
        if (param.getLatitude() != null && param.getLongitude() != null) {
            articlePO.setLocation(param.getLatitude() + "," + param.getLongitude());
        }

        // 4. 保留原始创建时间和删除状态
        articlePO.setCreateTime(existingPO.getCreateTime());
        articlePO.setDeleteStatus(existingPO.getDeleteStatus());

        // 5. 调用仓库层执行更新
        int rows = articleRepository.updateArticle(articlePO);
        if (rows <= 0) {
            return Result.fail("-1", "文章更新失败");
        }

        return Result.success();
    }


}